import { create } from 'zustand'

export const useTabStore = create(set => ({
  tabs: sessionStorage.getItem('tabs') ? JSON.parse(sessionStorage.getItem('tabs')) : [
    { key: '/home', label: '首页', closable: false }
  ],
  activeKey: sessionStorage.getItem('activeKey') || '/home',
  addTab: (route) => set(state => {
    // console.log('addTab', route)
    let tab = {
      ...route,
      key: route.path,
      label: route.handle.title || '未命名',
      closable: true
    }
    // console.log('addTab', tab)
    if (state.tabs.find(t => t.key === tab.key)) {
      // console.log('Tab already exists, activating it')
      if(tab.key !== state.activeKey){
        sessionStorage.setItem('activeKey', tab.key)
        return { activeKey: tab.key }
      }else {
        // 不更改任何数据
        return state
      }
    }
    let tabs = [...state.tabs, tab]
    let activeKey = tab.key
    sessionStorage.setItem('tabs', JSON.stringify(tabs))
    sessionStorage.setItem('activeKey', activeKey)
    return {
      tabs,
      activeKey
    }
  }),
  removeTab: (key, navigate) => set(state => {
    const tabs = state.tabs.filter(t => t.key !== key)
    let activeKey = state.activeKey
    if (activeKey === key && tabs.length) {
      activeKey = tabs[tabs.length - 1].key
    }
    sessionStorage.setItem('tabs', JSON.stringify(tabs))
    sessionStorage.setItem('activeKey', activeKey)
    navigate(activeKey)
    return { tabs, activeKey }
  }),
  setActiveKey: (key) => set(state => {
    sessionStorage.setItem('activeKey', key)
    return { activeKey: key }
  })
}))
